package com.zut.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.zut.constant.MessageConstant;
import com.zut.constant.RedisConstant;
import com.zut.entity.PageResult;
import com.zut.entity.QueryPageBean;
import com.zut.entity.Result;
import com.zut.pojo.Setmeal;
import com.zut.service.SetmealService;
import com.zut.utils.QiniuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.JedisPool;

import java.io.IOException;
import java.util.UUID;

/**
 * 体检套餐管理
 * @author sq
 * @create 2021-06-29-14:38
 */
@RestController
@RequestMapping("/setmeal")
public class SetmealController {
    //使用JedisPool操作Redis服务
    @Autowired//从当前Spring工厂中获取
    private JedisPool jedisPool;

    //从dubbo中远程调用服务实现类
    @Reference
    private SetmealService setmealService;

    //文件上传
    //@RequestParam注解：value属性的值是请求参数的名称（value可以省略）,后面定义的形参名称,即是它的别名。
    @RequestMapping("/upload")
    public Result upload(@RequestParam(value = "imgFile") MultipartFile imgFile){
        //获取原始的文件名
        String originalFilename = imgFile.getOriginalFilename();
        //获取文件名最后一个点的位置
        int index = originalFilename.lastIndexOf(".");
        //获取文件扩展名
        String extention = originalFilename.substring(index - 1);
        //自动生成36位的字符串，用来唯一标识文件名。
        String fileName = UUID.randomUUID().toString() + extention;
        try {
            //将文件上传到七牛云服务器上
            QiniuUtils.upload2Qiniu(imgFile.getBytes(),fileName);
            //将文件名存入到集合中，这时还不确定存入数据库，是大集合
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES,fileName);
        } catch (Exception e) {
            e.printStackTrace();
            //上传文件失败
            return new Result(false, MessageConstant.PIC_UPLOAD_FAIL);
        }
        return new Result(true, MessageConstant.PIC_UPLOAD_SUCCESS,fileName);
    }

    //添加套餐
    @RequestMapping("/add")
    public Result add(@RequestBody Setmeal setmeal, Integer[] checkgroupIds){
        try {
            //调用服务
            setmealService.add(setmeal,checkgroupIds);
            //新增套餐成功
            return new Result(true, MessageConstant.ADD_SETMEAL_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            //新增套餐失败
            return new Result(false, MessageConstant.ADD_SETMEAL_FAIL);
        }
    }

    //分页查询
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        return setmealService.pageQuery(queryPageBean);
    }

}
